package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
@Transactional
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Resource
    WemediaFeign wemediaFeign;

    @Resource
    ArticleFeign articleFeign;

    @Resource
    AdSensitiveMapper adSensitiveMapper;

    @Resource
    AdChannelMapper adChannelMapper;

    @Resource
    KafkaTemplate kafkaTemplate;

    @Override
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //参数校验
        if (wmNewsId == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //根据id查询文章数据
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        //判断文章是否存在
        if (wmNews == null) {
            log.error("文章不存在--->{}", wmNewsId);
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断文章状态
        //人工审核通过
        if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())) {
            //保存3张表数据
            saveAppArticle(wmNews);
        }

        //提交待审核状态，开始自动审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //TODO 自动审核
            //自定义敏感词校验
            Boolean isSensitiveScan = DataAudit(wmNews);
            //校验不通过直接结束
            if (!isSensitiveScan) {
                return;
            }
           /* //阿里内容检测
            //取出文章和图片数据
            List<Map> content = JSON.parseArray(wmNews.getContent(), Map.class);
            List<byte[]> images = parseContentImages(content);
            String Articles = parseContentArticle(content);
            //阿里文章审核
            boolean isTextScan = handleTextScan(Articles, wmNews);
            //校验不通过直接结束
            if (!isTextScan) {
                return;
            }
            //阿里图片审核
            boolean isImageScan = handleImageScan(images, wmNews);
            //校验不通过直接结束
            if (!isImageScan) {
                return;
            }*/
            //审核通过（待发布)修改文章状态8
            wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
            wemediaFeign.updateWmNews(wmNews);
            //保存3张表数据
            saveAppArticle(wmNews);

            //kafka发送消息同步es数据
            Map map = new HashMap();
            map.put("articleId", wmNews.getArticleId());
            kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD, JSON.toJSONString(map));
        }
       /* //审核通过（待发布)
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())) {
            //保存3张表数据
            saveAppArticle(wmNews);
        }*/

    }

    private boolean handleImageScan(List<byte[]> images, WmNews wmNews) {
        //无图则无需审核
        if (images == null || images.size() == 0) {
            return true;
        }
        try {
            Map map = GreenImageScan.imageScan(images);
            //审核不通过
            if (map.get("suggestion").equals("block")) {
                //修改为未通过
                wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("图片内容不通过：" + map);
                wemediaFeign.updateWmNews(wmNews);
                return false;
            }
            //人工审核
            if (map.get("suggestion").equals("review")) {
                //修改为人工审核
                wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("需要人工审核");
                wemediaFeign.updateWmNews(wmNews);
                return false;
            }


        } catch (Exception e) {
            log.error("阿里云图片审核失败，转为人工审核, e：{}", e);
            wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
            wmNews.setReason("需要人工审核");
            wemediaFeign.updateWmNews(wmNews);
            return false;
        }
        return true;
    }

    private boolean handleTextScan(String articles, WmNews wmNews) {
        //无内容则无需审核
        if (articles == null || StringUtils.isBlank(articles)) {
            return true;
        }
        try {
            Map map = GreenTextScan.greenTextScan(articles);
            if (map.size() > 0) {
                //审核不通过
                if (map.get("suggestion").equals("block")) {
                    //修改为未通过
                    wmNews.setStatus(WmNews.Status.FAIL.getCode());
                    wmNews.setReason("文章内容包含敏感词：" + map);
                    wemediaFeign.updateWmNews(wmNews);
                    return false;
                }
                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改为人工审核
                    wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                    wmNews.setReason("需要人工审核");
                    wemediaFeign.updateWmNews(wmNews);
                    return false;
                }
            }
        } catch (
                Exception e) {
            log.error("阿里云文章审核失败，转为人工审核, e：{}", e);
            wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
            wmNews.setReason("需要人工审核");
            wemediaFeign.updateWmNews(wmNews);
            return false;
        }
        return true;
    }

    private String parseContentArticle(List<Map> content) {
        return content.stream()
                .filter(map -> map.get("type").equals("text"))
                .map(text -> text + "_bzq_").collect(Collectors.joining());

    }


    private List<byte[]> parseContentImages(List<Map> contents) {
        return contents.stream() // 流式处理
                .filter(map -> map.get("type").equals("image")) // 过滤是图片
                .map(map -> (String) map.get("value")) // 映射处理->获取图片url
                .map(imageUrl -> imageUrl.replace(webSite, "")) // 映射处理->替换前缀路径
                .map(imageUrl -> imageUrl.getBytes())
                .collect(Collectors.toList()); // 将图片收集到一个图片集合中
    }


    private Boolean DataAudit(WmNews wmNews) {
        //查询自定义敏感词
        List<String> sensitives = adSensitiveMapper.findAllSensitive();

        //初始化敏感词列表
        SensitiveWordUtil.initMap(sensitives);
        //敏感词校验
        Map<String, Integer> map = SensitiveWordUtil.matchWords(wmNews.getContent());

        if (map.size() > 0) {
            //修改为未通过
            wmNews.setStatus(WmNews.Status.FAIL.getCode());
            wmNews.setReason("文章内容包含敏感词：" + map);
            wemediaFeign.updateWmNews(wmNews);
            return false;
        }
        return true;
    }


    private void saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //查询作者信息
        ApAuthor apAuthor = articleFeign.findByWmUserId(wmNews.getUserId());
        //判断作者信息是否为空
        if (apAuthor == null) {
            log.error("作者信息不存在--->{}", wmNews.getUserId());
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //封装dto
        BeanUtils.copyProperties(wmNews, dto);

        dto.setAuthorId(Long.valueOf(apAuthor.getId()));
        dto.setAuthorName(apAuthor.getName());
        //根据频道id查询频道名称
        AdChannel adChannel = adChannelMapper.selectOne(Wrappers.<AdChannel>lambdaQuery().eq(AdChannel::getId, wmNews.getChannelId()));
        if (adChannel == null) {
            log.error("频道信息不存在--->{}", wmNews.getChannelId());
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.setChannelName(adChannel.getName());
        dto.setLayout(wmNews.getType());
        dto.setFlag(Byte.valueOf("0"));

        //添加3张表的数据
        articleFeign.saveArticle(dto);
        //判断发布文章时间
        if (wmNews.getPublishTime().after(new Date()) || wmNews.getPublishTime() == null) {
            //发布文章
            wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
            wemediaFeign.updateWmNews(wmNews);
        }
    }
}
